package cn.com.cetccst.appstore.ui.activity;

import static cn.com.cetccst.appstore.ui.activity.viewmodel.AppStoreViewModel.TYPE_APP_LIST;
import static cn.com.cetccst.appstore.ui.activity.viewmodel.AppStoreViewModel.TYPE_UPGRADE;
import static cn.com.cetccst.appstore.ui.fragment.viewmodel.AppListViewModel.TYPE_NEED_UPGRADE;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.databinding.BindingAdapter;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import cn.com.cetccst.appstore.BR;
import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.databinding.ActivityAppStoreBinding;
import cn.com.cetccst.appstore.ui.activity.viewmodel.AppStoreViewModel;
import cn.com.cetccst.appstore.ui.fragment.AppListFragment;
import cn.com.cetccst.appstore.ui.fragment.StoreFragment;
import cn.com.cetccst.uicomponents.binding.app.DataBindingConfig;

public class AppStoreActivity extends BaseActivity<ActivityAppStoreBinding> {

    private AppStoreViewModel viewModel;
    private ClickProxy clickProxy;
    private Fragment currentFragment;
    private Fragment needUpgradeFragment;
    private Fragment appsFragment;

    @Override
    protected void initViewModel() {
        viewModel = getActivityScopeViewModel(AppStoreViewModel.class);
        clickProxy = new ClickProxy();
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_app_store, BR.viewModel, viewModel)
                .addBindingParam(BR.click, clickProxy);
    }

    @Override
    protected void onResume() {
        super.onResume();

//        String[] permissions = {WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE};
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//            permissions = new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, MANAGE_EXTERNAL_STORAGE};
//        }
//        //权限申请，回头再整理了
//        PermissionX.init(this)
//                //要申请的权限列表（可直接传入上方的requestList）
//                .permissions(permissions)
//                //（可选）修改默认对话框的颜色（浅色主题、深色主题）（默认已适配深色模式）
//                .setDialogTintColor(Color.parseColor("#008577"), Color.parseColor("#83e8dd"))
//                //（可选）在申请前先弹窗说明（下方通过beforeRequest区分）
//                .explainReasonBeforeRequest()
//                //弹窗申请原因（提供功能函数的上下文对象，被拒绝或者还未申请的权限清单，是否是申请前）
//                .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(
//                        deniedList, "下载应用需要申请存储权限", "同意", "拒绝"))
//                //针对被拒绝且不再询问的权限进行解释并跳转到系统设置
//                .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去应用程序设置当中手动开启权限", "我已明白"))
//                .request((allGranted, grantedList, deniedList) -> {
//                    if (!allGranted) {
//                        finish();
//                    }
//                });

        viewModel.pageType.observe(this, integer -> invalidateOptionsMenu());
        clickProxy.enterApps();
    }

    public class ClickProxy {
        public void enterApps() {
            viewModel.naviAppSelected.setValue(true);
            //业务简单，不做数据驱动处理
            showFragment(getAppsFragment());
            viewModel.pageType.setValue(TYPE_APP_LIST);
        }

        public void enterUpdatingApps() {
            viewModel.naviAppSelected.setValue(false);
            showFragment(getNeedUpgradeFragment());
            viewModel.pageType.setValue(TYPE_UPGRADE);
        }
    }

    private Fragment getNeedUpgradeFragment() {
        if (needUpgradeFragment == null) {
            needUpgradeFragment = new AppListFragment();
            Bundle bundle = new Bundle();
            bundle.putInt(AppListFragment.EXTRA_TYPE, TYPE_NEED_UPGRADE);
            needUpgradeFragment.setArguments(bundle);
        }
        return needUpgradeFragment;
    }

    private Fragment getAppsFragment() {
        if (appsFragment == null) {
            appsFragment = new StoreFragment();
        }
        return appsFragment;
    }

    private void showFragment(Fragment fragment) {

        int containerId = getBinding().fragmentContainer.getId();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (currentFragment == null) {
            ft.add(containerId, fragment);
        } else {
            if (currentFragment != fragment) {
                if (fragment.isAdded()) {
                    ft.hide(currentFragment).show(fragment);
                } else {
                    ft.hide(currentFragment).add(containerId, fragment);
                }
            }
        }
        if (!ft.isEmpty()) {
            ft.commit();
        }
        currentFragment = fragment;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        //分类不支持搜索
        if (viewModel.pageType.getValue() != TYPE_APP_LIST) {
            return true;
        }
        getMenuInflater().inflate(R.menu.appstore_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.search) {
            Intent intent = new Intent(this, SearchActivity.class);
            if (getBinding().bottomNaviUpdate.isSelected()) {
                intent.putExtra(SearchActivity.EXTRA_PAGE_TYPE, TYPE_UPGRADE);
            } else {
                intent.putExtra(SearchActivity.EXTRA_PAGE_TYPE, viewModel.pageType.getValue());
            }
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    //页面固有的Binding放在特定页面即可
    @BindingAdapter(value = {"naviSelected"})
    public static void viewSelected(final LinearLayout linearLayout, boolean selected){
        linearLayout.setSelected(selected);
    }

    @BindingAdapter(value = {"naviSelected"})
    public static void viewSelected(final RelativeLayout relativeLayout, boolean selected){
        relativeLayout.setSelected(selected);
    }

    @BindingAdapter(value = {"appSelected"})
    public static void appSelected(Button button, boolean selected) {
        button.setSelected(selected);
    }
}
